@()(implicit request: RequestHeader)
@user.main("差异分析（OPLS-DA）")("opls") {
	<div class="page-content">

		<div class="page-bar">
			<ul class="page-breadcrumb">
				<li>
					<i class="fa fa-opera"></i>
					<a href="#">差异分析（OPLS-DA）</a>
				</li>
			</ul>
		</div>


		<div class="row-fluid">

			<div class="row">
				<div class="col-md-12 col-sm-12">
					<div class="portlet green-jungle box">
						<div class="portlet-title">
							<div class="caption">
								设置参数
							</div>
						</div>

						<div class="portlet-body">

							<form class="registration-form form-horizontal" id="form"
							accept-charset="UTF-8" method="post">

								<div class="form-group" id="myGroup" >
									<label class="control-label col-sm-2">分组策略
										<a href="@routes.MetaboliteController.groupBefore()" target="_blank">
											<i style="color: black" class="fa fa-eye"></i></a> :</label>
									<div class="col-sm-3">
										<select class="form-control group" name="groupName" id="groupName" style="width: 100%" onchange="change()">

										</select>
									</div>
								</div>

								<div class="form-group">
									<label class="control-label col-sm-2">log2FC阈值:</label>
									<div class="col-sm-3">
										<input class="form-control" value="0" name="logCutoff">
									</div>
								</div>

								<div class="form-group">
									<h4 class="control-label col-sm-1">OPLS-DA</h4>
								</div>

								<div class="form-group">
									<h4 class="control-label col-sm-2" >分析参数</h4>
								</div>

								<div class="form-group">
									<label class="control-label col-sm-2">VIP阈值<span id="question1" style="margin-bottom: 5px">
										<a type="button" title="说明" data-container="body" data-toggle="popover"
										data-placement="right" data-content="OPLSDA_VIP_pred"
										data-trigger="hover"><i class="fa fa-question-circle-o"></i></a>
									</span>:</label>
									<div class="col-sm-3">
										<input class="form-control" value="1" name="vipCutoff">
									</div>

									<label class="control-label col-sm-2">
										log10变换<span id="question2" style="margin-bottom: 5px">
										<a type="button" title="说明" data-container="body" data-toggle="popover"
										data-placement="right" data-content="选&quot;是&quot;,输入矩阵在分析前将会进行log10变换；在变换前，0值将会被替换为1。"
										data-trigger="hover"><i class="fa fa-question-circle-o"></i></a>
									</span>:</label>
									<div class="col-sm-3">
										<select class="form-control" name="log10" required="required" style="border-radius: 4px;">
											<option value="T">是</option>
											<option value="F" selected="selected">否</option>
										</select>
									</div>
								</div>

								<div class="form-group">
									<label class="control-label col-sm-2">
										随机重排数<span id="question2" style="margin-bottom: 5px">
										<a type="button" title="说明" data-container="body" data-toggle="popover"
										data-placement="right" data-content="Number of random permutations of response labels to estimate R2Y and Q2Y significance by permutation testing."
										data-trigger="hover"><i class="fa fa-question-circle-o"></i></a>
									</span>:</label>
									<div class="col-sm-3">
										<select class="form-control" name="permI" required="required" style="border-radius: 4px;">
											<option value="0">0</option>
											<option value="20" selected>20</option>
											<option value="100">100</option>
											<option value="1000">1000</option>
										</select>
									</div>

									<label class="control-label col-sm-2">ScaleC:</label>
									<div class="col-sm-3">
										<select class="form-control" name="scaleC" required="required" style="border-radius: 4px;">
											<option value="none">either no centering nor scaling</option>
											<option value="center">mean-centering</option>
											<option value="pareto">mean-centering and pareto scaling</option>
											<option value="standard" selected>
												mean-centering and unit variance scaling</option>
										</select>
									</div>
								</div>

								<div class="form-group">

									<label class="control-label col-sm-2">crossvalI<span id="question1" style="margin-bottom: 5px">
										<a type="button" title="说明" data-container="body" data-toggle="popover"
										data-placement="right" data-content="Integer: number of cross-validation segments (default is 7);
										The number of samples (rows of 'x') must be at least >= crossvalI."
										data-trigger="hover"><i class="fa fa-question-circle-o"></i></a>
									</span>
										:</label>
									<div class="col-sm-3">
										<input class="form-control" value="7" name="crossValI">
									</div>

									<label class="control-label col-sm-2">orthoI<span id="question1" style="margin-bottom: 5px">
										<a type="button" title="说明" data-container="body" data-toggle="popover"
										data-placement="right" data-content="Integer: number of orthogonal components;when set to auto,
										OPLS is performed and the number of orthogonal components is automatically computed by using the cross-validation (with a maximum of 9 orthogonal components)."
										data-trigger="hover"><i class="fa fa-question-circle-o"></i></a>
									</span>:</label>
									<div class="col-sm-3">
										<select class="form-control" name="orthoI" required="required" style="border-radius: 4px;">
											<option value="NA">auto</option>
											<option value="1">1</option>
											<option value="2">2</option>
											<option value="3">3</option>
											<option value="4">4</option>
											<option value="5">5</option>
											<option value="6">6</option>
											<option value="7">7</option>
											<option value="8">8</option>
											<option value="9">9</option>
										</select>
									</div>


								</div>

								<div class="form-group">
									<h4 class="control-label col-sm-2">作图参数</h4>
								</div>

								<div class="form-group">
									<label class="control-label col-sm-2">输出图像类型:</label>
									<div class="col-sm-3">
										<select class="form-control" name="typeC" required="required" style="border-radius: 4px;">
											<option value="correlation">correlation</option>
											<option value="outlier">outlier</option>
											<option value="overview">overview</option>
											<option value="permutation">permutation</option>
											<option value="predict-train">predict-train</option>
											<option value="summary" selected>summary</option>
											<option value="x-loading">x-loading</option>
											<option value="x-score">x-score</option>
											<option value="x-variance">x-variance</option>
											<option value="xy-score">xy-score</option>
										</select>
									</div>

									<label class="control-label col-sm-2">画椭圆?</label>
									<div class="col-sm-3">
										<select class="form-control" name="parMahalC" required="required" style="border-radius: 4px;">
											<option value="T" selected>是</option>
											<option value="F">否</option>
										</select>
									</div>

								</div>

								<div class="form-group">
									<label class="control-label col-sm-2">文字相对大小:</label>
									<div class="col-sm-3">
										<input class="form-control" value="0.8" name="parCexN">
									</div>

								</div>

								<div class="form-group">
									<h4 class="control-label col-sm-1" >T检验参数</h4>
								</div>

								<div class="form-group" style="display: none">
									<label class="control-label col-sm-2">方法:</label>
									<div class="col-sm-3">
										<select class="form-control" name="method">
											<option value="tTest" selected="selected">T检验</option>
											<option value="uTest" >U检验</option>
										</select>
									</div>
								</div>

								<div class="form-group" id="paired">
									<label class="control-label col-sm-2">进行配对样品检验？</label>
									<div class="col-sm-3">
										<select class="form-control" name="paired">
											<option value="T">是</option>
											<option value="F" selected="selected">否</option>
										</select>
									</div>
								</div>

								<div class="form-group">
									<label class="control-label col-sm-2">p值阈值:</label>
									<div class="col-sm-3">
										<input class="form-control" value="0.05" name="pCutoff">
									</div>

									<label class="control-label col-sm-2">fdr阈值:</label>
									<div class="col-sm-3">
										<input class="form-control" value="1" name="qCutoff">
									</div>
								</div>

								<div class="form-group" id="varEqual">
									<label class="control-label col-sm-2">
										var.equal<span id="question1" style="margin-bottom: 5px">
										<a type="button" title="说明" data-container="body" data-toggle="popover"
										data-placement="right" data-content="a logical variable indicating whether to treat
										the two variances as being equal. If TRUE then the pooled variance is used to estimate the variance otherwise the Welch (or Satterthwaite) approximation to the degrees of freedom is used."
										data-trigger="hover"><i class="fa fa-question-circle-o"></i></a>
									</span>:</label>
									<div class="col-sm-3">
										<select class="form-control" name="varEqual">
											<option value="T">True</option>
											<option value="F" selected="selected">False</option>
										</select>
									</div>
								</div>



								<div class="form-group">
									<div class="actions col-sm-offset-2 col-sm-2">
										<button type="button" class="btn btn-primary" style="width: 90%;" id="search" onclick="mySearch()">
											运行</button>
									</div>
								</div>


							</form>

						</div>
					</div>
				</div>
			</div>

			<div id="result" style="display: none">

				<div class="row">
					<div class="col-md-12 col-sm-12">
						<div class="portlet green-jungle box">
							<div class="portlet-title">
								<div class="caption">
									代谢物变量结果
								</div>
								<div class="tools">
									<a href="javascript:;" class="collapse">
									</a>
								</div>
							</div>

							<div class="portlet-body" id="noCotent">暂无代谢物变量结果！</div>
							<div class="portlet-body" style="display: none;" id="content">

								<label>显示的列:</label>
								<div id="checkbox" class="checkbox">

								</div>

								<div class="table-responsive" id="tableContent">

									<table class="display table table-bordered" id="dataTable" data-pagination="true" data-search="true"
									data-toolbar="#toolbar" data-page-list="[10, 25, 50, 100, all]" data-multiple-search="true"
									data-show-export="true" data-export-types="['excel','txt']" data-export-data-type="all"
									>
										<thead>
											<tr>
												<th data-field='geneId' data-sortable='true' id="marker"
												data-formatter="diffMetaboliteIDFmt">代谢物</th>
											</tr>
										</thead>
									</table>

								</div>

								<div style="margin-top: 10px">
									<label>对差异代谢物进行:</label>
									<div class="row">

										<div class="col-sm-2">
											<form target="ncuTarget" method="post" id="geneIdForm">
												<input type="hidden" id="geneIdStr" name="geneIdStr">
												<input type="hidden" id="log2FcStr" name="log2FcStr">
											</form>
											<button type="button" class="btn btn-primary" style="width: 90%;" onclick="keggEnrich()">
												KEGG富集分析</button>
										</div>

										<div class="col-sm-2">
											<button type="button" class="btn btn-primary" style="width: 90%;" onclick="heatmap()">
												热图分析</button>
										</div>

										<div class="col-sm-2">
											<button type="button" class="btn btn-primary" style="width: 90%;" onclick="expressPattern()">
												表达模式分析</button>
										</div>

										<div class="col-sm-2">
											<button type="button" class="btn btn-primary" style="width: 90%;" onclick="roc()">
												Roc分析</button>
										</div>

									</div>
								</div>


							</div>
						</div>
					</div>
				</div>

				<div class="row">
					<div class="col-md-12 col-sm-12">
						<div class="portlet green-jungle box">
							<div class="portlet-title">
								<div class="caption">
									样品变量结果
								</div>
								<div class="tools">
									<a href="javascript:;" class="collapse">
									</a>
								</div>
							</div>

							<div class="portlet-body">

								<div class="table-responsive">

									<table class="display table table-bordered" id="sampleTable" data-pagination="true" data-search="true"
									data-toolbar="#toolbar" data-page-list="[10, 25, 50, 100, all]" data-multiple-search="true"
									data-show-export="true" data-export-types="['excel','txt']" data-export-data-type="all"
									style="table-layout: fixed;
										word-wrap: break-word"
									>
										<thead>
											<tr>
												<th data-field='name' data-sortable='true' title="Term">样品名</th>
												<th data-field='group' data-sortable='true' title="Database">
													组名</th>
												<th data-field='h1' data-sortable='true' title="ID">OPLSDA_XSCOR-h1</th>
												<th data-field='o1' data-sortable='true' title="Input number">
													OPLSDA_XSCOR-o1</th>
												<th data-field='preds' data-sortable='true' title="Background number">
													OPLSDA_predictions</th>
											</tr>
										</thead>
									</table>

								</div>

							</div>
						</div>
					</div>
				</div>


				<div class="row">
					<div class="col-md-12 col-sm-12">
						<div class="portlet green-jungle box">
							<div class="portlet-title">
								<div class="caption">
									图片结果
								</div>
								<div class="tools">
									<a href="javascript:;" class="collapse">
									</a>
								</div>
							</div>

							<div class="portlet-body">

								<div id="download" style="display: none;">
									<input type="hidden" id="pdfBase64">
									<button type="button" class="btn btn-primary" id="deleteButton" onclick="downloadPdf()"
									style="margin-bottom: 10px">
										<i class="fa fa-download"></i>&nbsp;下载pdf格式图片
									</button>
								</div>

								<div id="charts" align="center">
									<div >没有图片结果生成！</div>
								</div>
							</div>
						</div>
					</div>
				</div>


				<div class="row">
					<div class="col-md-12 col-sm-12">
						<div class="portlet green-jungle box">
							<div class="portlet-title">
								<div class="caption">
									引用
								</div>
							</div>
							<div class="portlet-body">
								<p class="paragraph">
									分析模块引用了<b>R语言ropls包（v1.6.2）</b>中的opls函数进行opls-da分析。
								</p>
								<p class="paragraph">
									相关文献如下所示：
								</p>
								<p class="paragraph">
									Eriksson et al. (2006). Multi- and Megarvariate Data Analysis. Umetrics Academy. Rosipal and Kramer (2006). Overview and recent advances in partial least squares Tenenhaus (1990). La regression PLS : theorie et pratique. Technip. Wehrens (2011). Chemometrics with R. Springer. Wold et al. (2001). PLS-regression: a basic tool of chemometrics
								</p>

							</div>

						</div>
					</div>
				</div>
			</div>


		</div>

	</div>


	<script>
			var originalHtml = ""
			$(function () {
				originalHtml = $("#tableContent").html()

				$('#sampleTable').bootstrapTable({
					exportOptions: {
						csvSeparator: "\t"
					}
				});

				$.ajax({
					url: "@routes.MetaboliteController.getAllGroupNum2Names()",
					type: "get",
					success: function (data) {
						$(".group").select2({
							data: data,
							minimumResultsForSearch: -1
						})
						change()
					}
				})

				bootstrapValidator()
			})

			function change() {
				var value = $("#groupName").find(">option:selected").val()
				$("#paired select").val("F")
				$.ajax({
					url: "@routes.MetaboliteController.checkRelation()",
					type: "get",
					data: {
						"groupName": value
					},
					success: function (data) {
						if (data == "True") {
							$("#paired").show()
						} else {
							$("#paired").hide()
						}
					}
				})
			}

			function base642binaryArray(content) {
				var byteCharacters = atob(content);
				var byteArrays = [];
				var sliceSize = 512
				for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
					var slice = byteCharacters.slice(offset, offset + sliceSize);
					var byteNumbers = new Array(slice.length);
					for (var i = 0; i < slice.length; i++) {
						byteNumbers[i] = slice.charCodeAt(i);
					}
					var byteArray = new Uint8Array(byteNumbers);
					byteArrays.push(byteArray);
				}
				return byteArrays
			}

			function downloadPdf() {
				var fileName = "figure.pdf"
				var content = $("#pdfBase64").val()
				var byteArrays = base642binaryArray(content)
				var blob = new Blob(byteArrays, {
					type: "application/pdf"
				})
				saveAs(blob, fileName)
			}

			function keggEnrich() {
				$("#geneIdForm").attr("action", "@routes.MetaboliteController.keggEnrichBefore1()")
				$("#geneIdForm").submit()
			}

			function heatmap() {
				$("#geneIdForm").attr("action", "@routes.MetaboliteController.heatmapBefore1()")
				$("#geneIdForm").submit()
			}

			function expressPattern() {
				$("#geneIdForm").attr("action", "@routes.MetaboliteController.expressPatternBefore1()")
				$("#geneIdForm").submit()
			}

			function roc() {
				$("#geneIdForm").attr("action", "@routes.MetaboliteController.rocBefore1()")
				$("#geneIdForm").submit()
			}

			function mySearch() {
				var form = $("#form")
				var fv = form.data("bootstrapValidator")
				fv.validate()
				if (fv.isValid()) {
					var element = "<div id='content'><span id='info'>" + zhRunning + "</span>&nbsp;<img class='runningImage' src='@routes.Assets.at("images/running2.gif")' style='width: 30px;height: 20px;'></div>"
					var index = layer.alert(element, {
						skin: 'layui-layer-molv'
						, closeBtn: 0,
						title: zhInfo,
						btn: []
					});

					$.ajax({
						url: "@routes.MetaboliteController.opls()",
						type: "post",
						data: $("#form").serialize(),

						success: function (data) {
							layer.close(index)
							if (data.valid == "false") {
								$("#charts").html("没有图片结果生成！")
								$("#noCotent").show()
								$("#content").hide()
								$("#download").hide()
								swal("Error", data.message, "error")
								$("#result").hide()
							} else {
								refreshContent(data)
								$('#sampleTable').bootstrapTable("load", data.sampleData);
								groupName = $("#groupName").val()
								$("#noCotent").hide()
								$("#content").show()
								$("#charts").html(data.base64)
								$("#pdfBase64").val(data.pdfBase64)
								$("#download").show()
								$("#geneIdStr").val(data.geneIdStr)
								$("#log2FcStr").val(data.log2FcStr)
								$("#result").show()
							}
						}
					});

				}
			}

			function refreshContent(data) {
				var checkboxHtml = ""
				$.each(data.columnNames, function (i, v) {
					checkboxHtml += "<label style='margin-right: 15px'>" +
							"<input type='checkbox' checked='checked' value='" + v + "' onclick=\"setColumns('" + v + "')\">" + v +
							"</label>"
				})
				$("#checkbox").empty().append(checkboxHtml)
				var html = ""
				$.each(data.columnNames, function (i, v) {
					html += "<th data-field='" + v + "' data-sortable='true' title='" + v + "'>" + v + "</th>"
				})
				$("#tableContent").empty().append(originalHtml)
				$("#marker").after(html)
				$('#dataTable').bootstrapTable({
					data: data.array,
					exportOptions: {
						csvSeparator: "\t"
					}
				});
				$.each(data.columnNames.slice(10), function (n, value) {
							$('#dataTable').bootstrapTable('hideColumn', value);
							$("input:checkbox[value='" + value + "']").attr("checked", false)
						}
				);
				var hideArray=["t-test.fdr","OPLSDA_XLOAD-o1","OPLSDA_XLOAD-h1"]
				$.each(hideArray, function (n, value) {
							$('#dataTable').bootstrapTable('hideColumn', value);
							$("input:checkbox[value='" + value + "']").attr("checked", false)
						}
				);

			}

			function bootstrapValidator() {
				var infinityNumber = Number.MAX_VALUE
				$('#form').bootstrapValidator({
					framework: 'bootstrap',
					icon: {
						valid: 'glyphicon glyphicon-ok',
						invalid: 'glyphicon glyphicon-remove',
						validating: 'glyphicon glyphicon-refresh'
					},
					fields: {
						vipCutoff: {
							validators: {
								notEmpty: {
									message: "vip值阈值不能为空！"
								},
								numeric: {
									message: "vip值阈值必须为数字！"
								}
							}
						},
						logCutoff: {
							validators: {
								notEmpty: {
									message: 'log2FC阈值不能为空！'
								},
								numeric: {
									message: "log2FC阈值必须为数字！"
								}
							}
						},
						crossValI: {
							validators: {
								notEmpty: {
									message: "crossValI值不能为空！"
								},
								integer: {
									message: "crossValI值必须为数字！"
								}
							}
						},
						parCexN: {
							validators: {
								notEmpty: {
									message: "文本比例不能为空！"
								},
								numeric: {
									message: "文本比例必须为数字！"
								}
							}
						},
						groupName: {
							validators: {
								callback: {
									message: '请至少选择一个分组策略！',
									callback: function (value, validator, $field) {
										var options = validator.getFieldElements('groupName').val();
										return (options != null);
									}
								}
							}
						},
						pCutoff: {
							validators: {
								notEmpty: {
									message: 'p值阈值不能为空！'
								},
								numeric: {
									message: "p值阈值必须为数字！"
								},
								between: {
									min: "0",
									max: 1,
									message: "p值阈值必须在0到1之间！"
								}
							}
						},
						qCutoff: {
							validators: {
								notEmpty: {
									message: "fdr阈值不能为空！"
								},
								numeric: {
									message: "fdr阈值必须为数字！"
								},
								between: {
									min: 0,
									max: 1,
									message: "fdr阈值必须在0到1之间！"
								}
							}
						},


					}
				});
			}

			function setColumns(value) {
				var element = $("input:checkbox[value='" + value + "']")
				if (element.is(":checked")) {
					$('#dataTable').bootstrapTable('showColumn', value);
				} else {
					$('#dataTable').bootstrapTable('hideColumn', value);
				}
			}
	</script>

}